#include <git2.h>
#include <stdio.h>
#include <string.h>

int main() {
	git_libgit2_init();
	char *repo_path = "test_repos";
	git_repository *repo;
	int ret = git_repository_open(&repo ,repo_path);
	if(ret<0) {
		printf("git_repository_open failed, error msg:%s\n", giterr_last()->message);
	}
	printf("open ok\n");

	////remote
	//printf("repository remote_names:\n");
	//git_strarray remote_names;
	//git_remote_list(&remote_names, repo);
	//for (int i = 0; i < remote_names.count; ++i) {
	//	printf("%s\n", remote_names.strings[i]);
	//}
	//git_strarray_free(&remote_names);

	git_remote *remote = NULL;
	if(git_remote_lookup(&remote, repo, "origin") < 0) {
		printf("git_remote_lookup failed, error msg:%s\n", giterr_last()->message);
		return -1;
	}

	git_strarray fetch_refspecs, push_refspecs;
	git_remote_get_fetch_refspecs(&fetch_refspecs, remote);
	git_remote_get_push_refspecs(&push_refspecs, remote);
	printf("remote name:%s, url:%s\n", git_remote_name(remote), git_remote_url(remote));
	printf("remote fetch refspecs:\n");
	for(int i=0; i < fetch_refspecs.count; ++i) {
		printf("%s\n", fetch_refspecs.strings[i]);
	}
	printf("remote push refspecs:\n");
	for(int i=0; i < push_refspecs.count; ++i) {
		printf("%s\n", push_refspecs.strings[i]);
	}

	printf("remote connect:%d\n", git_remote_connected(remote));
	git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
	if(git_remote_connect(remote, GIT_DIRECTION_FETCH, &callbacks, NULL) < 0) {
	}
	printf("remote connect:%d\n", git_remote_connected(remote));
	git_fetch_options fetch_opts = GIT_FETCH_OPTIONS_INIT;

	//git_remote_fetch(remote, &fetch_refspecs, &fetch_opts, NULL)
	if(git_remote_fetch(remote, NULL, &fetch_opts, NULL) < 0) {
		printf("git_remote_fetch failed, error msg:%s\n", giterr_last()->message);
		return -1;
	}

	const git_transfer_progress *stats = git_remote_stats(remote);
	if (stats->local_objects > 0) {
		printf("\rReceived %lld/%lld objects in %lld bytes (used %lld local objects)\n",
		       stats->indexed_objects, stats->total_objects, stats->received_bytes, stats->local_objects);
	} else{
		printf("\rReceived %lld/%lld objects in %lld bytes\n",
			stats->indexed_objects, stats->total_objects, stats->received_bytes);
	}
	git_remote_free(remote);

	git_repository_free(repo);
	return 0;
}